<template>
	<view class="index-view">
		<view style="height: 30rpx;"></view>
		<view class="address-info" @click="selectAddress" v-if="addressList.length > 0">
			<template v-for="item in addressList">
				<template v-if="item.isDefault == 0">
					<view class="left" :key="item.id">
						<view class="top">
							<u-icon name="map" color="#000" size="13"></u-icon>
							<h2>{{item.userName}}</h2>
							<span>{{item.phone}}</span>
						</view>
						<view class="ad-de">
							<span v-if="item.isDefault == 0" class="defalt-btn">默认</span>
							<span class="detail">{{item.province}}{{item.city}}{{item.proCityArea}}{{item.detailedAddress}}</span>
						</view>
					</view>
					<u-icon :key="item.id" name="arrow-right" size="16" color="#000"></u-icon>
				</template>
			</template>
		</view>
		<view class="address-info" @click="selectAddress" v-if="addressList.length === 0">
			<view class="left">
				<view class="top">
					<u-icon name="map" color="#000" size="13"></u-icon>
					<h2>{{pitchAddress.userName}}</h2>
					<span>{{pitchAddress.phone}}</span>
				</view>
				<view class="ad-de">
					<span
						class="detail">{{pitchAddress.province}}{{pitchAddress.city}}{{pitchAddress.proCityArea}}{{pitchAddress.detailedAddress}}</span>
				</view>
			</view>
			<u-icon name="arrow-right" size="16" color="#000"></u-icon>
		</view>
		<view class="goods-info">
			<view class="goods-item" v-for="item in goodsList" :key="item.id">
				<view class="img-box">
					<image class="goods-img" :src="item.pic" mode="aspectFit"></image>
				</view>
				<view class="right">
					<h2>{{ item.productName }}<span v-if="item.tag">{{item.tag || ''}}</span></h2>
					<view class="info_text u-line-1" @click="changeSku(item)">
						<view class="icon-text">{{item.skuName}}</view>
						<!-- 向下箭头 -->
						<view class="icon-down-box">
							<u-icon class="icon-down" name="arrow-down" size="14" color="#999999"></u-icon>
						</view>
					</view>
					<view class="s-c">
						<b>
							￥<span>{{ item.price }}</span>
						</b>
						<u-number-box integer button-size="15" :min="1" iconStyle="fontSize:24rpx"
							v-model="item.num"></u-number-box>
					</view>
				</view>
			</view>
		</view>
		<view class="form-box" style="padding-top:10rpx;padding-bottom:20rpx;margin-bottom:120rpx">
			<view class="item-li">
				<text style="font-size: 24rpx;">商品总价</text>
				<view class="right" style="color:#F21331">
					￥{{totalPrice}}
				</view>
			</view>
			<view class="item-li">
				<text style="font-size: 24rpx;">运费</text>
				<view class="right">
					<view style="color:#F21331;margin-right: 5rpx;">0</view>
				</view>
			</view>
			<view class="item-li">
				<text style="font-size: 24rpx;">店铺优惠</text>
				<view class="right">
					<view style="color:#F21331;margin-right: 5rpx;">0</view>
				</view>
			</view>
			<view class="item-li">
				<text style="font-size: 24rpx;">优惠券</text>
				<view class="right" @click="couponClick()">
					<view style="color:#F21331;margin-right: 5rpx;">
						<template v-if="discountAmount!=0">
							<text>-</text>
							{{discountAmount}}
						</template>
					</view>
					<u-icon name="arrow-right" v-if="discountAmount===0"></u-icon>
				</view>
			</view>
		</view>
		<view class="footer">
			<text></text>
			<!-- <text class="cancel">取消订单</text> -->
			<text class="btn" @click="placeOrder">提交订单</text>
		</view>

		<u-popup :show="selShow" :round="10" @close="close" closeable bgColor="#f2f2f2">
			<view class="sel-container-cart">
				<!-- <view class="commodity">
					<image class="commodity-img" :src="product.pic"></image>
					<view class="commodity-right">
						<view class="header-title">{{product.productName}}</view>
						<view class="header-number">
							商品编号:{{product.id}}
						</view>
					</view>
				</view> -->
				<view class="title">
					选择规格
				</view>
				<view class="popup-container">
					<u-radio-group shape="circle" v-model="skuName" placement="column" @change="groupChange"
						activeColor="#8551EB">
						<u-radio :customStyle="{marginBottom: '8px'}" v-for="item in skuList" :key="item.id" :label="item.skuName"
							:name="item.skuName" @change="radioChange">
						</u-radio>
					</u-radio-group>
					<!-- <u-icon class="duihao" name="checkmark-circle-fill" size="40" color="#8551EB" @tap="toDuibi('',2)"></u-icon> -->
				</view>
			</view>
		</u-popup>

		<u-popup :show="coupon" :round="10" @close="coupon = false" closeable bgColor="#f2f2f2">

			<view class="bigBox">
				<view class="boxTitle">
					我的优惠券（{{notUseCouponList.length}}）
				</view>
				<view class="couponList" v-if="notUseCouponList.length > 0">
					<view class="couponItem flex_heng" :style="{background:`url(${imgUrl}notcoupon.png) no-repeat`}"
						v-for="item,index in notUseCouponList" :key="index">
						<view class="price">
							<span>￥</span>{{item.discountAmount}}
						</view>
						<view class="itemContent flex_shu">
							<view class="itemName">
								{{item.name}}
							</view>
							<view class="itemType">
								满 {{item.conditionAmount}}元 可用
							</view>
							<view class="itemTime">
								有效期至{{item.endTime}}
							</view>
						</view>
						<view class="btn" @click="goUseIt(item)">
							去使用
						</view>
					</view>
				</view>
				<view style="padding:40rpx" v-if="notUseCouponList.length === 0">
					<u-empty :icon="imgUrl + 'empty-youhui.png'" mode="data" text="暂无优惠活动" />
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import {
		getAddressList,
		putCart,
		createOrder,
		getProductById,
		getUserCouponList,
		getOrderListDetails
	} from '@/api/api.js'

	export default {
		data() {
			return {
				imgUrl: this.$imgUrl,
				iStatusBarHeight: 0,
				iTitleBarHeight: 48,
				orderId: '',
				orderInfo: {
					id: '51518151',
					totalPrice: '8999',
					freight: '15',
					goodsInfo: {
						id: 213213,
						goodsName: '海尔GX1558',
						img: 'https://gw.alicdn.com/imgextra/O1CN01jCB4eW1T1WayEtqBe_!!108072322.jpg_.webp',
						sku: '596mm超薄嵌入/535大筒径/超微浸泡洗/1.1超高洗净比',
						price: '7858',
						oriPrice: '8888'
					}
				},
				// 选中的地址信息
				pitchAddress: {},
				// 我的地址列表
				addressList: [],
				goodsList: [],
				selShow: false,
				curId: '',
				skuName: '',
				skuList: [],
				coupon: false,
				notUseCouponList: [],
				useCouponList: [],
				overdueCouponList: [],
				discountAmount: 0,
				appCouponId: '',
				waterNumber: '',
				product: {},
			}
		},
		onLoad(op) {
			this.iStatusBarHeight = uni.getSystemInfoSync().statusBarHeight;
			this.iTitleBarHeight = uni.getSystemInfoSync().titleBarHeight;
			this.waterNumber = op.waterNumber
			this.getOrderListDetails(op.waterNumber)
		},
		onShareAppMessage(e) {
			console.log(e);
		},
		onShow() {
			// this.goodsList = uni.getStorageSync('orderInfo');
		},
		computed: {
			totalPrice() {
				let total = 0;
				if (this.goodsList.length === 0) return 0
				this.goodsList.forEach(item => {
					total += item.price * item.num
				})
				return total - this.discountAmount
			}
		},
		methods: {

			// 获取订单
			getOrderListDetails(waterNumber) {
				getOrderListDetails({
					waterNumber
				}).then(res => {
					this.goodsList = res.rows.map(item => {
						return {
							...JSON.parse(item.productData),
							skuName: JSON.parse(item.skuData).skuName,
							skuId: JSON.parse(item.skuData).id,
							num: 1,
						}
					})
					this.pitchAddress = JSON.parse(res.rows[0].addressData);
				})
			},

			// 去使用
			goUseIt(item) {
				this.discountAmount = item.discountAmount // 优惠金额
				this.appCouponId = item.id // 优惠券id
				this.coupon = false
			},

			couponClick() {
				this.coupon = true;
				this.getUserCouponList(1);
			},
			//用户优惠券
			getUserCouponList(status) {
				getUserCouponList({
					pageNum: this.page,
					pageSize: 1000,
					status,
					appUserId: uni.getStorageSync('userInfo').id,
				}).then(res => {
					if (res.code == 200) {
						console.log(res);
						if (status === 1) {
							this.notUseCouponList = res.rows; // 1-待使用
						} else if (status === 2) {
							this.useCouponList = res.rows; // 2已过期
						} else if (status === 3) {
							this.overdueCouponList = res.rows; //  3-已使用
						}
					}
				})
			},


			// 获取商品详情 的 SKU
			getProductById(id) {
				getProductById(id).then(res => {
					this.product = res.data;
					this.skuList = res.data.skuList;
				})
			},

			changeSku(item) {
				this.selShow = true;
				this.getProductById(item.id);
				this.curId = item.id;
				this.$nextTick(() => {
					this.skuName = item.skuName;
				})
			},

			close() {
				this.selShow = false
			},

			groupChange(n) {
				console.log('groupChange', n);
				const sku = this.skuList.find(res => res.skuName === n);

				this.goodsList.map(item => {
					if (item.id == this.curId) {
						item.skuId = sku.id;
						item.skuName = sku.skuName;
						item.price = sku.price;
					}
				})
				this.close();
			},
			radioChange(n) {
				console.log('radioChange', n);
			},


			// 提交订单
			placeOrder() {
				// 商品
				const productList = this.goodsList.map(e => {
					return {
						"productId": e.id,
						"num": e.num,
						"skuId": e.skuId,
					}
				})

				// 获取地址ID
				let addressId = "";

				if (this.addressList.length === 0) {
					if (this.pitchAddress.id) {
						addressId = this.pitchAddress.id;
					} else {
						uni.showToast({
							title: '请选择地址',
							icon: 'none'
						})
						return;
					}
				} else {
					const address = this.addressList.find(e => e.isDefault === 0);
					if (address) {
						addressId = address.id;
					} else {
						uni.showToast({
							title: '请选择地址',
							icon: 'none'
						})
						return;
					}
				}

				const _this = this;

				uni.showModal({
					content: "是否提交订单？",
					mask: true,
					success: function(res) {
						if (res.confirm) {
							createOrder({
								"addressId": addressId,
								"appCouponId": _this.appCouponId, // 优惠券ID
								"appUserId": uni.getStorageSync('userInfo').id,
								"productList": productList, // 选中的商品
								"shoppingCartList": [], //选中的购物车
							}).then(res => {
								if (res.code == 200) {
									console.log(res.data);
									// 微信支付
									uni.requestPayment({
										provider: 'wxpay',
										timeStamp: res.data.timeStamp,
										nonceStr: res.data.nonceStr,
										package: res.data.packageValue,
										signType: res.data.signType,
										paySign: res.data.paySign,
										success: function(res) {
											console.log('success:' + JSON.stringify(res));
											// 跳转订单管理
											// 提示支付成功
											uni.showToast({
												type: 'success',
												title: '支付成功',
											})
											setTimeout(() => {
												uni.navigateTo({
													url: `/package/pages/orderManagement/orderManagement`
												})
											}, 800)

										},
										fail: function(res) {
											console.log('fail:' + JSON.stringify(res));
											// 跳转等待支付
											uni.$u.toast('支付失败')
											setTimeout(() => {
												uni.navigateTo({
													url: `/package/pages/orderManagement/orderManagement`
												})
											}, 800)
										}
									})
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},

			// 选择地址
			selectAddress() {
				uni.navigateTo({
					url: '/package/pages/myAddress/myAddress?from=order'
				})
			},

			// 购物车数量变化
			numChange(val, item) {
				putCart({
					id: item.id,
					num: val.value
				}).then(res => {
					if (res.code == 200) {
						console.log('修改成功');
					}
				})
			},

			// 获取默认地址
			getList() {
				uni.showLoading({
					title: '请稍候...',
					mask: true
				})
				const data = {
					page: 1,
					num: 50,
					userId: uni.getStorageSync('userInfo').id
				}
				getAddressList({
					params: data
				}).then(res => {
					uni.hideLoading()
					if (res.code == 200) {
						console.log(res);
						uni.hideLoading()
						this.addressList = res.rows
					}
				})

			},


			goBack() {
				uni.navigateBack()
			},
			getDetail() {

			},
		}
	}
</script>

<style lang="scss">
	.item-li {
		margin-top: 20rpx;

		.right {
			display: flex;
			justify-content: flex-end;
			align-items: center;
		}
	}

	.index-view {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
		box-sizing: border-box;

		.address-info {
			background-color: #fff;
			padding: 38rpx 20rpx;
			box-sizing: border-box;
			border-radius: 27rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin: 0 33rpx;
			margin-bottom: 30rpx;

			.left {
				.top {
					display: flex;
					align-items: center;
					font-size: 26rpx;

					h2 {
						color: #000;
						margin: 0 6rpx;
					}

					span {
						color: #999;
						font-weight: 200;
						font-family: 'hm-os-text';
					}
				}

				.btm {
					font-size: 24rpx;
					margin-top: 20rpx;
					color: #999;
					font-weight: 200;
					font-family: 'hm-os-text';
				}
			}
		}

		.goods-info {
			background-color: #fff;
			padding: 38rpx 20rpx;
			box-sizing: border-box;
			border-radius: 27rpx;
			margin: 0 33rpx 0;

			.goods-item {
				display: flex;
				padding-bottom: 10rpx;
				margin-bottom: 20rpx;

				.img-box {
					width: 175rpx;
					height: 175rpx;
					margin-right: 20rpx;
					background-color: #f7f7f7;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 17rpx;

					.goods-img {
						max-width: 100%;
						border-radius: 17rpx;
					}
				}

				.right {
					flex: 1;

					display: flex;
					flex-direction: column;
					justify-content: space-between;

					h2 {
						font-size: 28rpx;
						color: #000000;
						font-family: 'biaoti';
						display: flex;
						align-items: center;

						span {
							margin-left: 8rpx;
							padding: 4rpx 8rpx;
							box-sizing: border-box;
							color: #fff;
							font-size: 20rpx;
							font-family: 'hm-os-text';
							background-color: #8551EB;
							border-radius: 8rpx;
						}
					}

					p {
						font-size: 21rpx;
						color: #000000;
						font-family: 'hm-os-med';
						margin: 16rpx 0 51rpx;
					}

					.add-cart {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.price {
							display: flex;
							align-items: center;

							b {
								font-size: 22rpx;
								color: #F21331;
								font-family: 'hm-os-label';
							}

							span {
								font-size: 40rpx;
								color: #F21331;
								font-family: 'biaoti';
								transform: translateY(-5rpx);
							}

							.ori-price {
								text-decoration: line-through;
								font-size: 24rpx;
								color: #666;
								font-family: 'hm-os-text';
								margin-left: 8rpx;
							}
						}

						image {
							width: 44rpx;
							height: 44rpx;
						}
					}
				}
			}
		}

		.form-box {
			margin: 20rpx 33rpx;

			.title {
				font-size: 26rpx;
				color: #000000;
				padding: 20rpx 20rpx 0;
				box-sizing: border-box;
			}

			.line {
				margin: 0 8rpx;
			}

			.copy {
				color: #8551EB;
			}
		}

		.footer {
			position: fixed;
			bottom: 0;
			width: 100%;
			height: 100rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 26rpx;
			font-family: 'hm-os-med';
			padding: 0 33rpx;
			box-sizing: border-box;

			.cancel {
				color: #999;
			}

			.btn {
				background-color: #F21331;
				color: #fff;
				padding: 15rpx 46rpx;
				box-sizing: border-box;
				border-radius: 40rpx;
			}
		}
	}

	.info_text {
		width: 120rpx;
		height: 27rpx;
		line-height: 31rpx;
		padding: 3px 5px;
		background: #EBEBEB;
		border-radius: 7rpx 7rpx 7rpx 7rpx;
		font-weight: 300;
		font-size: 24rpx;
		color: #999999;
		display: flex;
		align-items: center;
		justify-content: center;

		position: relative;

		.icon-text {
			padding-right: 8rpx;
		}

		.icon-down-box {
			position: absolute;
			right: 7rpx;
			top: 11rpx;
		}
	}

	.s-c {
		width: 100%;
		font-weight: bold;
		font-size: 26rpx;
		color: #F64D48;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.u-number-box__input {
			background-color: transparent !important;
			font-weight: 400;
			font-size: 24rpx;
			color: #333333;
		}

		span {
			font-size: 32rpx;
		}

	}

	.ad-de {
		box-sizing: border-box;

		.defalt-btn {
			font-weight: 400;
			font-size: 20rpx;
			color: #FF787E;
			background-color: rgba(253, 105, 105, 0.25);
			width: 70rpx;
			height: 36rpx;
			text-align: center;
			line-height: 36rpx;
			display: inline-block;
		}

		.detail {
			font-weight: 400;
			font-size: 28rpx;
			color: #666666;
			margin-left: 16rpx;
		}
	}

	.sel-container-cart {

		padding-bottom: 80rpx;

		.commodity {
			background-color: #fff;
			padding: 20rpx;
			display: flex;
			align-items: center;
			justify-content: flex-start;

			.commodity-img {
				width: 160rpx;
				height: 160rpx;
				border-radius: 20rpx;
				background-color: #F5F5F5;
				margin-right: 40rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.commodity-right {
				flex: 1;

				.commodity-title {
					font-family: 'biaoti';
					font-weight: bold;
					font-size: 28rpx;
					color: #000;
					overflow: hidden;
				}

				.header-number {
					margin-top: 10rpx;
					font-size: 22rpx;
					color: #444;
				}
			}
		}

		.title {
			height: 126rpx;
			width: 100%;
			font-size: 35rpx;
			color: #000000;
			font-family: 'biaoti';
			line-height: 96rpx;
			text-align: center;
		}

		.popup-container {
			padding: 0 33rpx;
			box-sizing: border-box;
			position: relative;
		}
	}


	.bigBox {
		background: #FFFFFF;
		border-radius: 27rpx;
		padding: 24rpx 40rpx;
		box-sizing: border-box;

		margin: 91rpx 30rpx;

		.boxTitle {
			font-family: biaoti;
			font-size: 28rpx;
			color: #8551EB;
			font-weight: bold;
			margin-left: 42rpx;
		}

		.couponList {

			.couponItem {
				margin-top: 28rpx;
				width: 100%;
				height: 168rpx;
				background-size: 100% 100% !important;
				justify-content: space-around;

				.price {
					font-family: biaoti;
					font-weight: normal;
					color: #A26A2B;
					font-size: 80rpx;
					width: 200rpx;
					text-align: center;

					span {
						font-size: 34rpx;
					}
				}

				.itemContent {
					font-family: hm-os-label;
					color: #FFECC9;
					align-items: flex-start;

					.itemName {
						font-size: 28rpx;
					}

					.itemType {
						font-size: 22rpx;
					}

					.itemTime {
						font-size: 16rpx;
					}
				}

				.btn {
					width: 101rpx;
					height: 55rpx;
					text-align: center;
					line-height: 55rpx;
					border-radius: 27rpx;
					border: 1rpx solid #FFECC9;
					font-family: hm-os-label;
					font-size: 22rpx;
					color: #FFECC9;
				}

				.btnTwo {
					width: 101rpx;
					height: 55rpx;
					text-align: center;
					line-height: 55rpx;
					border-radius: 27rpx;
					border: 1rpx solid #FFFFFF;
					font-family: hm-os-label;
					font-size: 22rpx;
					color: #FFF;
				}
			}
		}
	}

	.flex_heng {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: space-between;
		align-items: center;
	}

	.flex_shu {
		display: flex;
		flex-direction: column;
		flex-wrap: nowrap;
		justify-content: space-between;
		align-items: center;
	}
</style>